// ==UserScript==
// @name         登录凭证上传
// @namespace    http://tampermonkey.net/
// @version      0.0.1
// @description  登录凭证上传
// @author       momo@516801525@qq.com
// @match        *://*/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=jinritemai.com
// @run-at       document-end
// @grant        GM_xmlhttpRequest
// @grant        GM_cookie
// @grant        GM_registerMenuCommand
// @grant        GM_addStyle
// @grant        GM_getResourceText
// ==/UserScript==

function getCookiesByDomain(domain) {
    return new Promise((resolve, reject) => {
        GM_cookie.list({ domain: domain }, (cookies) => {
            if (cookies) {
                resolve(cookies);
            } else {
                reject(new Error('获取Cookie失败'));
            }
        });
    });
}

async function mtCookieUpload(data){

    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            url:"https://mt.hedaochaincloud.com/api/account/meituan",
            method :"POST",
            data:JSON.stringify(data),
            headers: {
                "Content-Type": "application/json",
            },
            onload:function(xhr){
                let res = JSON.parse(xhr.responseText)
                resolve(res)
            }
        });
    })
}



(async function() {
    'use strict';
    // 核心判断：如果当前窗口不是顶层窗口（即处于iframe中），则退出执行
    if (window.top !== window.self) {
        console.log('脚本在iframe中，不执行');
        return; // 直接退出，不执行后续代码
    }
    const currentDomain = window.location.hostname;
    console.log("----------------",currentDomain,currentDomain == "pos.meituan.com")
    if (currentDomain == "pos.meituan.com"){
        GM_registerMenuCommand("美团登录回传", async ()=>{
            let cookies = await getCookiesByDomain("pos.meituan.com")
            cookies = cookies.concat(await getCookiesByDomain(".meituan.com"));
            let cookieUn = {}
            cookies.forEach((item)=>{
                if(!cookieUn[item["name"]]){
                    cookieUn[item["name"]] = item["name"] + "=" + item["value"]
                }else{
                    if(item["domain"] == ".pos.meituan.com"){
                        cookieUn[item["name"]] = item["name"] + "=" + item["value"]
                    }
                }
            })
            cookieUn = Object.values(cookieUn);
            cookieUn = cookieUn.join("; ")
            const postData = {
                cookie:cookieUn
            }
            await mtCookieUpload(postData)
            alert("登录信息回传成功")
        })
    }

})();
